<template>
  <div class="orderDetail-box">
    <div class="header">
      <h5>新增售后单</h5>
      <i class="iconfont icon-close" @click.prevent="close"></i>
    </div>
    <div style="padding-left: 20%">
      <el-form class="form-box" :model="ruleForm" ref="ruleFormRef" :rules="rules">
        <el-form-item prop="orderId" label="选择订单号">
          <label>
            <button @click.prevent="openOrder">{{ruleForm.orderId?ruleForm.orderId:'选择订单号'}}</button>
          </label>
        </el-form-item>
        <el-form-item prop="aftersaleInfo" label="售后详情">
          <label>
            <el-input v-model="ruleForm.aftersaleInfo" placeholder="售后详情" />
          </label>
        </el-form-item>
        <el-form-item prop="aftersalePhoto"  label="上传售后详情图">
          <label>
            <div>
              <div class="upload" @click.prevent>
                <ImageUpload
                  :limit="6"
                  @update:modelValue="handlerModelValue"
                  :fileType="fileType"
                  :modelValue="dialogImageUrl"
                />
                <el-dialog v-model="dialogVisible">
                  <img w-full :src="dialogImageUrl" alt="售后详情" />
                </el-dialog>
              </div>
            </div>
          </label>
        </el-form-item>

        <el-form-item class="btn-box">
          <el-button @click="resetForm(ruleFormRef)" style="background: #f2f3f5">重置</el-button>
          <el-button type="primary" @click.stop="submitForm(ruleFormRef)"> 提交 </el-button>
        </el-form-item>
      </el-form>
    </div>



    <PopUps widthMy="60%" height-my="78%"   v-if="flagOrder" >
      <div class="optionsOrder">
        <header>选择订单号</header>
          <el-form
            :inline="true"
            :model="optionsOrderForm"
            ref="optionsOrderFormRef"
            class="form-inline"
          >
            <el-form-item label="下单日期" class="startTime" prop="orderDate">
              <el-date-picker
                clearable
                v-model="optionsOrderForm.orderDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="单据编号" prop="orderId">
              <el-input v-model="optionsOrderForm.orderId" />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="optionsOrderForm.customerId"
                popper-class="deptIdSelect"
                @visible-change="selectChange($event, customerId, 'customerName')"
                clearable
              >
                <el-input
                  v-model="customerModel"
                  style="width: 90%"
                  @input="InputSearchChangeHandler(customerId, 'customerName')"
                >
                  <template #prefix>
                    <el-icon class="el-input__icon">
                      <search />
                    </el-icon>
                  </template>
                </el-input>
                <template v-if="customerNameData">
                  <el-option
                    :label="item.customerName"
                    :value="item.customerId"
                    v-for="item in customerNameData"
                    :key="item.customerId"
                  />
                </template>
                <template v-if="Array.isArray(customerNameData) && customerNameData.length === 0">
                  <el-option
                    :label="item.customerName"
                    :value="item.customerId"
                    v-for="item in customerId"
                    :key="item.customerId"
                  />
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="optionsOrderForm.deptId"
                popper-class="deptIdSelect"
                clearable
                @visible-change="selectChange($event, deptId, 'deptName')"
              >
                <el-input
                  v-model="deptIdModel"
                  @input="InputSearchChangeHandler(deptId, 'deptName')"
                  style="width: 90%"
                >
                  <template #prefix>
                    <el-icon class="el-input__icon">
                      <search />
                    </el-icon>
                  </template>
                </el-input>

                <template v-if="deptIdData">
                  <el-option
                    :label="item.deptName"
                    :value="item.deptId"
                    v-for="item in deptIdData"
                    :key="item.deptId"
                  />
                </template>
                <template v-if="Array.isArray(deptIdData) && deptIdData.length === 0">
                  <el-option
                    :label="item.deptName"
                    :value="item.deptId"
                    v-for="item in deptId"
                    :key="item.deptId"
                  />
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="制单人" prop="creator">
              <el-input v-model="optionsOrderForm.creator" />
            </el-form-item>
            <el-form-item>
              <div class="btn">
                <el-button type="primary" @click="onQuery" class="submit">查询</el-button>
                <el-button
                  type="primary"
                  @click="onReset(optionsOrderFormRef)"
                  color="#E4E9FC"
                  class="reset"
                >重置
                </el-button>
              </div>
            </el-form-item>
          </el-form>

        <div class="invoiceStatus">
          <header>单据状态</header>
          <forTableCom
            :color="color"
            :idActive="idActive"
            :bg="bg"
            @handleSelectionChange="handleSelectionChange"
            :tableHeaderData="inventoryTableHeaderData"
            :pagination="false"
            :tableData="inventoryTableData"
            height="270"
            @scrollhandler="scrollhandler"
            class="forTableComOrder"
          >
          </forTableCom>

          <div class="btnSub">
            <el-button type="primary" @click.stop="onAdd" class="add">确认</el-button>
            <el-button type="primary" @click.stop="onCancel" class="cancel" color="#E4E9FC"
            >取消</el-button
            >
          </div>
        </div>
      </div>
    </PopUps>
  </div>
</template>
<script setup>
import { reactive, ref, defineEmits, defineProps } from 'vue'
import { checkPermi } from '@/utils/permission.js'
import { inputSearchHandler } from '@/hook/inputChange'
import forTableCom from '@/components/forTableCom/index.vue'

import ImageUpload from '@/components/ImageUpload/index.vue'
import PopUps from '@/components/My/PopUps/index.vue'
import { ElMessage } from 'element-plus'
import {
  getdepartmentseApi,
  getselectOrderApi,
  getWorkApi,
  getworkInsertApi,
} from '@/api/tickets/index.js'
import { sliceDate } from '@/utils/date.js'
import { insertAfterSaleOrderApi } from '@/api/teams/index.js'
const { proxy } = getCurrentInstance();

let color = '#000'
let idActive = 'orderId'
let bg = '#F6F8FE'
const optionsOrderFormRef = ref(null)

const emit = defineEmits(['closePopUps'])
const dialogVisible = ref(false)
const flagOrder = ref(false)
const dialogImageUrl = ref('')
const ruleFormRef = ref(null)
const rules = reactive({
  orderId: [{ required: true, message: '请选择订单号', trigger: 'blur' }],
  aftersaleInfo: [{ required: true, message: '请填写售后详情', trigger: 'blur' }],
  aftersalePhoto: [{ required: true, message: '请上传售后详情图”', trigger: 'change' }],
})
// 图片类型
let fileType = ['png', 'jpg', 'jpeg', 'jfif']
const ruleForm = reactive({
  orderId: '',
  aftersaleInfo: '',
  aftersalePhoto: [],
})
// rowDataDetail
const props = defineProps({
  // 订单详情信息
  rowDataDetail: {
    type: Object,
    default: [],
    required: true,
  },
  widthMy: {
    type: String,
  },
})
// 存放的设计及图
let designDrawings = reactive([])
// 关闭当前框
const close = () => {
  emit('closePopUps', false)
}
// 获取的图片
const handlerModelValue = async (v) => {
  ruleForm.aftersalePhoto = v
}
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let params = {
        aftersalePhoto: JSON.stringify(ruleForm.aftersalePhoto),
        aftersaleInfo: ruleForm.aftersaleInfo,
        orderId: ruleForm.orderId,
      }
      insertAfterSaleOrderApi(params).then(res => {
        if(res.code === 200) {
          proxy.$modal.msgSuccess(res.msg);
          emit('closePopUps', false)
        }
      })
    } else {
      console.log('提交失败', fields)
    }
  })
}
// 重置
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  dialogImageUrl.value = ''

}

// 部门下拉数据
let deptId = ref([])
// 部门绑定的值
let deptIdModel = ref('')
// 部门搜索下拉数据
let deptIdData = ref([])

// 客户名称
let customerId = ref([])
// 客户名绑定的值
let customerModel = ref('')
// 客户搜索下拉数据
let customerNameData = ref([])
// 订单号选择
let optionOrderList = ref()
// 显示搜索到的值
let { SearchHandler } = inputSearchHandler()

const openOrder = ()=>{
  flagOrder.value = true
}
// 在 Input 值改变时发送
const InputSearchChangeHandler = (searchValue, i) => {
  // hook
  // SearchHandler(v, arr, searchobj, includesName)
  switch (i) {
    case 'customerId':
      // 客户名
      customerNameData.value = SearchHandler(searchValue, customerModel, i)
      break
    case 'deptName':
      // 部门
      deptIdData.value = SearchHandler(searchValue, deptIdModel, i)
      break

    default:
      break
  }
}
// 选择订单表单
const optionsOrderForm = ref({
  orderDate: '', // 单据日期
  orderId: '', // 单据编号
  customerId: '', // 客户名称
  deptId: '', // 部门
  creator: '', // 制单人
})
// 选择订单号
const inventoryTableHeaderData = ref([
  {
    prop: 'orderDate',
    label: '单据日期',
  },
  {
    prop: 'orderId',
    label: '单据编号',
  },
  {
    prop: 'customerId',
    label: '客户名称',
  },
  {
    prop: 'businessType',
    label: '业务类型',
  },
  {
    prop: 'productionContent',
    label: '制作内容',
  },
  {
    prop: 'invoiceStatus',
    label: '单据状态',
  },
  {
    prop: 'paymentStatus',
    label: '结款状态',
  },
  {
    prop: 'totalOrderAmount',
    label: '订单总金额',
  },
  {
    prop: 'creator',
    label: '制单人',
  },
])
// 选择订单号的表格数据
const inventoryTableData = ref([])
// 创建表格一行表格
const createTable = (data) => {
  if (props.disabled) return
  dataTable.value.push(data)
}
// 删除表格一行表格
const deleteRow = (v) => {
  dataTable.value.splice(v.$index, 1)
}
// 封装请求下拉菜单信息
const getDropDownData = (res) => {
  let { code, data } = res
  if (code == 200) {
    return data
  }
}
// 获取部门下拉菜单数据
const getdeptIdseApiData = async (data = '') => {
  let params = { deptName: data }
  let res = await getdepartmentseApi(params)
  deptId.value = getDropDownData(res)
}
// 第一次进入获取一级二级弹窗的客户下拉数据
const getCustomerData = (res) => {
  customerId.value = getDropDownData(res)
  let rowList = []
  res.data.forEach((v) => {
    rowList.push({
      value: v.customerId,
      label: v.primaryClassification + '/' + v.customerName,
    })
  })
}
// 获取客户下拉菜单数据
const getWorkApiData = async (data = '', contcatData = true) => {
  let params = { customerId: data }
  let res = await getWorkApi(params)
  if (contcatData) {
    getCustomerData(res)
  } else {
    // 关联 客户地址 客户电话 客户
    popUpsForm.value.contactPhone = res.data[0].contactPhone
    popUpsForm.value.customerContacts = res.data[0].customerContacts
    popUpsForm.value.customerAddress = res.data[0].address
  }
}
// 关闭拉下时清除搜索框的值
const selectChange = (event, v, v1) => {
  if (event == false) {
    customerModel.value = ''
    deptIdModel.value = ''
    InputSearchChangeHandler(v, v1)
  }
}
// 选择订单号查询
const onQuery = () => {
  let params = {
    orderDate: optionsOrderForm.value.orderDate, // 单据日期
    orderId: optionsOrderForm.value.orderId, // 单据编号
    customerId: optionsOrderForm.value.customerId, // 客户名称
    deptId: optionsOrderForm.value.deptId, // 部门
    creator: optionsOrderForm.value.creator, // 制单人
  }
  getselectOrderData(params)
}
// 选择订单号重置
const onReset = (ref) => {
  if (!ref) return
  ref.resetFields()
}
// 选择的列
const handleSelectionChange = (v) => {
  optionOrderList.value = v
}
// 订单号确认
const onAdd = () => {
  if (optionOrderList.value.length == 1) {
    ruleForm.orderId = optionOrderList.value[0].orderId
    flagOrder.value = false
  } else {
    ElMessage({
      type: 'warning',
      message: '只能勾选一个@^@',
    })
  }
}
// 取消
const onCancel = () => {
  flagOrder.value = false
}
let pageNum = ref(1) // 页数
let pageSize = ref(50) // 条数
let totals = ref(12)
// 工单详情接口
const getselectOrderData = async (params = '') => {
  let res = await getselectOrderApi(params)
  let { code, rows, total } = res
  if (code === 200) {
    sliceDate(rows, 'orderDate')
    totals.value = total
    inventoryTableData.value = []
    rows.forEach((v, i) => {
      inventoryTableData.value.push(v)
      inventoryTableData.value[i].customerId = v.customerName
      inventoryTableData.value[i].businessType = v.productionVOS[0]?.businessType
      inventoryTableData.value[i].productionContent = v.productionVOS[0]?.productionContent
    })
  }
}
// 滑动到底部
const scrollhandler = () => {
  let params = {
    pageNum: pageNum.value++,
    pageSize: pageSize.value + 12,
  }
  // 数据请求对比优化
  if (totals.value > inventoryTableData.value.length) {
    getselectOrderData(params)
  }
}

onMounted(() => {
  getWorkApiData()
  getdeptIdseApiData()
  getselectOrderData()
})
</script>
<style scoped lang="scss">
.optionsOrder {
  padding: 20px 20px 0 20px;
  height: 100%;

  header {
    margin-bottom: 20px;
    font-weight: 550;
  }



  .btnSub {
    width: 100%;
    text-align: right;
    margin-top: 30px;

    .el-button {
      width: 50px;
      height: 25px;
      font-size: 12px;
    }
  }
}
:deep(.el-form-item) {
  width: 100% !important;
}
.orderDetail-box {
  width: 100%;
  height: 100%;
  overflow-y: scroll;

  .未完成 {
    color: red;
  }

  .已支付 {
    color: green;
  }

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #1947ff;
    border-radius: 4px 4px 0px 0px;
    padding: 0 30px;
    height: 40px;
    width: 100%;

    h5 {
      color: #fff;
      font-weight: 600;
    }

    .icon-close {
      border: 1px solid #666;
      color: #1947ff;
      background: #ffffff;
    }
  }

  .form-box{
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100% !important;
    align-items: center;
  }

  .content {
    padding-top: 40px;
    color: #333333;

    .content-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
    }

    .content-main {
      padding: 0 20px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .list-left,
      .list-right {
        display: flex;
        align-items: center;
        width: 33.33%;

        p {
          height: 40px;
          line-height: 40px;
        }
      }

      .desc-list {
        display: flex;
        align-items: center;
        width: 100%;

        .desc-right {
          margin: 5px 0;

          .el-textarea {
            width: 800px;
          }
        }
      }
    }

    .content-bottom {
      padding: 0 20px;
      display: flex;
      justify-content: space-between;

      .bottom-left {
        margin-top: 10px;
        display: flex;

        p {
          color: #1947ff;
        }
      }

      .bottom-right {
        margin: 40px 0;

        p {
          width: 58px;
          height: 28px;
          background: linear-gradient(180deg, #d8e0ff 0%, #ffffff 100%);
          box-shadow: 2px 3px 6px 1px rgba(0, 0, 0, 0.16);
          border-radius: 2px 2px 2px 2px;
          text-align: center;
          line-height: 28px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
